package com.ckw.match.filter;

import com.ckw.match.mapper.MatchMapper;
import com.ckw.question.mapper.RecordMapper;
import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Component
public class BloomFilterInitializer {

    private static BloomFilter<CharSequence> bloomFilter;

    @Autowired
    private MatchMapper matchMapper;

    @PostConstruct
    public void init() {
        // 预计插入的元素数量
        int expectedInsertions = 10000;
        // 期望的误判率
        double fpp = 0.01;

        bloomFilter = BloomFilter.create(Funnels.stringFunnel(StandardCharsets.UTF_8), expectedInsertions, fpp);

        // 从数据库中获取所有的 mid
        List<Long> allMids = matchMapper.getAllMids();
        for (Long mid : allMids) {
            bloomFilter.put(String.valueOf(mid));
        }
    }

    public void addMid(long mid) {
        bloomFilter.put(String.valueOf(mid));
    }

    public static boolean mightContain(long mid) {
        return bloomFilter.mightContain(String.valueOf(mid));
    }
}